"use client";

import { eventToKeyName } from "@/src/libs/keycode";
import { MacroAction } from "@/src/types/types.v1";
import { Box, Img } from "@chakra-ui/react";
import { useState } from "react";
import { ArrowUpFill } from "@/src/icons/ArrowUpFill";
import { ArrowUp } from "@/src/icons/ArrowUp";
import { ArrowDownFill } from "@/src/icons/ArrowDownFill";
import { ArrowDown } from "@/src/icons/ArrowDown";

function MacroKeyAction({
  action,
  onChange,
}: {
  action: MacroAction;
  onChange: (action: MacroAction) => void;
}) {
  const [edit, setEdit] = useState(false || action.webCode === "");

  const changeKey = (event: any) => {
    onChange({ ...action, webCode: event.code });
    setEdit(false);
  };

  const changeActionUp = () => {
    onChange({
      ...action,
      action: action.action === "keydown" ? "keyup" : "keydown",
    });
  };

  const changeActionDown = () => {
    onChange({
      ...action,
      action: action.action === "keyup" ? "keydown" : "keyup",
    });
  };

  return (
    <div
      className="min-w-16 text-center border border-gray-300 hover:border-blue-1 aria-selected:border-blue-1 aria-selected:border-2 bg-[#2b2d31] rounded-lg relative macro-key-action"
      aria-selected={edit}
    >
      <Box
        className="triangle-top"
        data-action={action.action}
        onClick={() => changeActionUp()}
      >
        {/* <Img
          src={`svgs/arrow_down${
            action.action == "keydown" ? "_fill" : ""
          }.svg`}
          alt="up"
        /> */}
        {action.action == "keydown" ? <ArrowDownFill /> : <ArrowDown />}
      </Box>
      {edit && (
        <input
          onKeyDown={changeKey}
          onBlur={() => setEdit(false)}
          autoFocus
          className=" opacity-0 w-0 h-0 absolute top-0 left-0"
        />
      )}
      <Box
        onClick={() => setEdit(true)}
        className="p-4 text-sm font-bold select-none !min-h-14"
      >
        {eventToKeyName(action.webCode || "")}
      </Box>
      <Box
        className="triangle-bottom"
        data-action={action.action}
        onClick={() => changeActionDown()}
      >
        {/* <Img
          src={`svgs/arrow_up${action.action == "keyup" ? "_fill" : ""}.svg`}
          alt="up"
        /> */}
        {action.action == "keyup" ? <ArrowUpFill /> : <ArrowUp />}
      </Box>
    </div>
  );
}

export default MacroKeyAction;
